package com.zlsy.thread.lock.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhouliang
 * @date 2020/7/28 19:56
 */
public class LockInterruptiblyTest implements Runnable {
    private Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        LockInterruptiblyTest lockInterruptiblyTest = new LockInterruptiblyTest();
        Thread t1 = new Thread(lockInterruptiblyTest, "线程1");
        Thread t2 = new Thread(lockInterruptiblyTest, "线程2");
        t1.start();
        t2.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.interrupt();
    }

    @Override
    public void run() {
//        try {
//            lock.lockInterruptibly();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } finally {
//            //你都不知道是否拿到锁就去解锁，肯定不行的！
//            lock.unlock();
//        }

        System.out.println(Thread.currentThread().getName() + "尝试获取锁！");
        try {
            lock.lockInterruptibly();
            try {
                System.out.println(Thread.currentThread().getName() + "获取到了锁");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + ":睡眠期间被中断。");
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + "释放了锁！");
            }
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + "等待获取锁期间被中断。");
        }
    }
}
